package com.powernode.teatraceability.interceptors;


import com.powernode.teatraceability.dao.basicinfomgt.EnterpriseMapper;
import com.powernode.teatraceability.dao.login.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * ClassName: AuthorizeInterceptor
 * Description:
 *
 * @Author: jdz
 * @Create: 2023/4/21 - 23:29
 */
@Component
@Slf4j
public class AuthorizeInterceptor implements HandlerInterceptor {
    @Resource
    UserMapper userMapper;
    @Resource
    EnterpriseMapper enterpriseMapper;

    /**
     * Spring Security 的过滤器链是在请求到达 DispatcherServlet 之前执行的
     * 如果一个请求没有通过身份认证，
     * 那么它将被 Spring Security 拦截并重定向到登录页面或返回 401（未授权）错误，
     * 不会进入到这个拦截器中。
     * 因此，只有经过身份认证的用户才能通过并访问这个拦截器, 得发一次除excludePathPatterns("/api/auth/**");之外的请求
     *
     * 用于在请求处理前,从 Spring Security 中获取当前已认证的用户信息，
     * 并将其保存到 HttpSession
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        final SecurityContext context = SecurityContextHolder.getContext();
        final Authentication authentication = context.getAuthentication();
        final User user = (User) authentication.getPrincipal();
        System.out.println(authentication);
        final String username = user.getUsername();
        log.info(String.valueOf(user));
        log.info(username);
        final com.powernode.teatraceability.pojo.login.User accountUser = userMapper.findAccountUserByNameOrEmail(username);
        accountUser.setQymc(enterpriseMapper.selectQYMCByQydm(accountUser.getQydm()));
        request.getSession().setAttribute("user", accountUser);
        return true;
    }
}
